package com.example.safeassistan.my.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.StringUtils;
import com.example.safeassistan.utile.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class ActivityBindPhone  extends BaseActivity implements View.OnClickListener {
    private TextView tvGetCode,tvBind;
    private ImageView ivClear;
    private EditText etLoginPhone,etCheckCode;
    private String phone="",codes="";


    private Integer type=0;
    public static void actionStart(Context context,Integer type) {
        Intent intent = new Intent(context, ActivityBindPhone.class);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvGetCode:
                //获取验证码
                getMobileMsgCode();
                break;
            case R.id.tvBind:
                //绑定新手机号
                bindPhone();
                break;
            case R.id.ivClear:
                //清空手机号
                phone="";
                etLoginPhone.setText("");
                break;
        }
    }


    /**
     * 获取手机验证码
     */
    private void getMobileMsgCode() {
        JSONObject object = new JSONObject();
        try {
            object.put("phone", phone);
            object.put("type", "1");//类型  1修改绑定手机号 2修改密码

        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(this).doPost(UrlConstants.sms_send, "", object, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
//                                new Thread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        for (int i = 60; i > 0; i--) {
//                                            handler.sendEmptyMessage(CODE_ING);
//                                            if (i <= 0) {
//                                                break;
//                                            }
//                                            try {
//                                                Thread.sleep(1000);
//                                            } catch (InterruptedException e) {
//                                                e.printStackTrace();
//                                            }
//                                        }
//                                        handler.sendEmptyMessage(CODE_REPEAT);
//                                    }
//                                }).start();
                            etCheckCode.setText(model.getResult().toString());
                            codes=model.getResult().toString();
                        }
                    }else {
                        ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success1,message,1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e(TAG,msg);
            }
        });
    }


    private void bindPhone() {
        JSONObject object = new JSONObject();
        try {
            object.put("code",codes);
            object.put("phone", phone);
            object.put("type", "1");//类型  1修改绑定手机号 2修改密码

        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(this).doPost(UrlConstants.updMobile, "", object, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
                            UserData.create(ActivityBindPhone.this).changeUserData(UserData.PHONE,phone);
                            Toast.makeText(ActivityBindPhone.this,"手机号操作成功",Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }else {
                        ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success1,message,1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e(TAG,msg);
            }
        });
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_change_phone;
    }

    @Override
    protected void initView() {
        type=getIntent().getIntExtra("type",0);
        if (type==0){
            //修改手机号
            setTitleText("修改手机号");
        }else {
            setTitleText("绑定手机号");
        }

        tvGetCode=findViewById(R.id.tvGetCode);
        tvGetCode.setOnClickListener(this::onClick);
        tvBind=findViewById(R.id.tvBind);
        tvBind.setOnClickListener(this::onClick);
        ivClear=findViewById(R.id.ivClear);
        ivClear.setOnClickListener(this::onClick);
        etLoginPhone=findViewById(R.id.etLoginPhone);
        etLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    phone=s.toString();
                }catch (Exception e){
                    phone="";
                }
                if(phone.length()>0){
                    ivClear.setVisibility(View.VISIBLE);
                }else {
                    ivClear.setVisibility(View.GONE);
                }
                checkStatus();
            }
        });
        etCheckCode=findViewById(R.id.etCheckCode);
        etCheckCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    codes=s.toString();
                }catch (Exception e){
                    codes="";
                }
                checkStatus();
            }
        });
    }

    public void checkStatus(){
        if(StringUtils.isPhoneNumber(phone) &&codes.length()>=4){
            tvBind.setClickable(true);
            tvBind.setBackgroundResource(R.drawable.login_checked_bg);
        }else {
            tvBind.setClickable(false);
            tvBind.setBackgroundResource(R.drawable.login_unchecked_bg);
        }
    }

    @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return 0;
    }
}
